//
//  AppDelegate+DTCAppService.m
//  BluetoothProject
//
//  Created by JianWei Chen on 16/9/5.
//  Copyright © 2016年 JianWei Chen. All rights reserved.
//

#import "AppDelegate+DTCAppService.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AudioToolbox/AudioToolbox.h>

#import <KSCrash/KSCrashInstallationStandard.h>
//#import "GetAreaListApi.h"

#define NOTIFY_NET_CHANGE @"notifyNetChange"

@interface AppDelegate ()<DTCBluetoothManagerDelegate,AMapLocationManagerDelegate>
/** 定位 **/
//@property(nonatomic,strong) AMapLocationManager *locationManager;

@end

@implementation AppDelegate (DTCAppService)

- (void)setNetworkBaseConfig
{
    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
    config.baseUrl = ServerURL;
}


/**
 *  蓝牙配置设置
 */
- (void)setBluetoothManagerConfig
{
//    NSLog(@"现在：%li",(long)[self getNowTimeSp]);
    [DTCBluetoothManager shareInstance].delegate = self;
    [[DTCBluetoothManager shareInstance] scanAroundDevice];//自主控制设备扫描操作
    [[DTCBluetoothManager shareInstance]setFilterDeviceByServiceUUID:@[@"FFE0"] onDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        if (([peripheralName rangeOfString:@"RPPZ"].location != NSNotFound && peripheralName.length!= 0)) {
            return YES;
        }
        return NO;
    }];//设备过滤条件

}

- (void)setWindowBaseConfig
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [[IQKeyboardManager sharedManager]setEnable:YES];
    [[IQKeyboardManager sharedManager]setKeyboardDistanceFromTextField:100];
}


#pragma mark - 代理
#pragma mark - <DTCBluetoothManagerDelegate>
- (void)dtcBluetoothManagerCentralManagerState:(CBManagerState)state
{
    if ([self checkLostNotificationTime] && state == 4) {
        
        NSString *sound = [NSString string];
        if (DTCEXRACT_OBJECT(@"notDisturb") == nil || [DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"NO"]) {
            sound = @"alarm.caf";
        } else {
            sound = @"silent.caf";
        }
        
        UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"警告" message:@"设备已经断开连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alterView show];
        
        [[DTCLocalPushManager defalutService]addLocalNotificationByBody:@"设备已经断开连接" sound:sound date:[NSDate dateWithTimeIntervalSince1970:[[NSDate date]timeIntervalSince1970]+5] userInfo:@{@"report":@"disconnect"} repeat:NO];
        
        [self location];
    }
//    else if ([self checkLostNotificationTime] && state == 4) {
//        
//    }
}

- (void)dtcBluetoothManagerConnectSuccessByDevice:(DTCDeviceModel *)deviceModel
{
    DTCSAVE_OBJECT(@"YES", MATCH);
    [[DTCBluetoothDataBaseManager sharedInstance] addDevice:deviceModel];
    
    NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:@"YES",@"blueConnect", nil];
    NSNotification *notification =[NSNotification notificationWithName:@"matchMachine" object:nil userInfo:dict];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    
    UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"设备连接成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alterView show];

}

- (void)dtcBluetoothManagerDisConnectByDevice:(DTCDeviceModel *)deviceModel
{
    if ([self checkLostNotificationTime]) {
        
        NSString *sound = [NSString string];
        if (DTCEXRACT_OBJECT(@"notDisturb") == nil || [DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"NO"]) {
            sound = @"alarm.caf";
        } else {
            sound = @"silent.caf";
        }
        
        UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"警告" message:@"设备已经断开连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alterView show];
        
        [[DTCLocalPushManager defalutService]addLocalNotificationByBody:@"设备已经断开连接" sound:sound date:[NSDate dateWithTimeIntervalSince1970:[[NSDate date]timeIntervalSince1970]+5] userInfo:@{@"report":@"disconnect"}  repeat:NO];
        
        [self location];
    }

}

- (void)dtcBluetoothManagerSearchDeviceChange:(NSArray *)deviceList
{
    NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:@"YES",@"blueList", nil];
    NSNotification *notification =[NSNotification notificationWithName:@"matchMachine" object:nil userInfo:dict];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}

- (void)dtcBluetoothManagerReadDataBack:(NSData *)data andNotifyCharacteristic:(NSString *)characterValue sendByDevice:(DTCDeviceModel *)deviceModel
{
    NSLog(@"dtcBluetoothManagerReadData %@ %@ %@",deviceModel,data,characterValue);
}

- (void)dtcBluetoothManagerWriteDataBack:(NSData *)data andNotifyCharacteristic:(NSString *)characterValue sendByDevice:(DTCDeviceModel *)deviceModel
{
    
}

- (void)dtcBluetoothManagerConnectFailByDevice:(DTCDeviceModel *)deviceModel error:(NSError *)error
{
    NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:@"YES",@"blueFail", nil];
    NSNotification *notification =[NSNotification notificationWithName:@"matchMachine" object:nil userInfo:dict];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}

- (void)dtcBluetoothManagerDiscoverCharacteristicSerice:(DTCDeviceModel *)deviceModel characeristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    
}

- (BOOL)checkLostNotificationTime{
    NSArray *data = [LostModel selectAllObject];
    for (LostModel *lost in data) {
        if (lost.switchMark) {
            NSArray *array = [lost.repeat componentsSeparatedByString:@"  "];
            if ([lost.repeat isEqualToString:@"永不"]) {
                NSInteger now = [[NSDate date] timeIntervalSince1970];
                if (lost.time <= now && now <= (lost.time+24*60*60)) {
                    if ([self checkTimeInWithStartTime:lost.startTime andEndTime:lost.endTime]) {
                        return YES;
                    }
                }
            } else {
                for (NSString *string in array) {
                    if ([string isEqualToString:[self getWeek]]) {
                        if ([self checkTimeInWithStartTime:lost.startTime andEndTime:lost.endTime]) {
                            return YES;
                        }
                    }
                }

            }

        }
    }
    return NO;
}

//- (BOOL)checkLostNotificationTime{
//    NSArray *data = [NSArray array];
//    data = DTCEXRACT_OBJECT(@"lost");
//    for (NSDictionary *dict in data) {
//        if ([dict[@"switch"] isEqualToString:@"YES"]) {
//            NSArray *array = [dict[@"repeat"] componentsSeparatedByString:@"  "];
//            if ([DTCEXRACT_OBJECT(@"onlyOne") isEqualToString:@"YES"]) {
//                DTCSAVE_OBJECT(@"NO", @"onlyOne");
//                return YES;
//            } else {
//                for (NSString *string in array) {
//                    if ([string isEqualToString:[self getWeek]]) {
//                        if ([self checkTimeInWithStartTime:dict[@"startTime"] andEndTime:dict[@"endTime"]]) {
//                            return YES;
//                        }
//                    }
//                }
//
//            }
//       }
//    }
//    return NO;
//}

- (BOOL) checkTimeInWithStartTime:(NSString *)startTime andEndTime:(NSString *)endTime {
//    NSLog(@"时间戳%li",[self timeSwitchTimestamp:[NSString stringWithFormat:@"%@ 11:22",[self getYearMouthDay]]]);
    NSInteger start = [self timeSwitchTimestamp:[NSString stringWithFormat:@"%@ %@",[self getYearMouthDay],startTime]];
    NSInteger end = [self timeSwitchTimestamp:[NSString stringWithFormat:@"%@ %@",[self getYearMouthDay],endTime]];
    NSInteger now = [self getNowTimeSp];
//    NSLog(@"开始：%li,现在：%li,结束：%li",(long)start,(long)now,(long)end);
    if (start < now && now < end) {
        return YES;
    }
    
    return NO;
}

#pragma mark -- 设备断开连接时记录当前位置信息
- (void)location {
    AMapLocationManager *locationManager = [[AMapLocationManager alloc] init];
    locationManager.delegate = self;
    [locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //    iOS 9（不包含iOS 9） 之前设置允许后台定位参数，保持不会被系统挂起
    [locationManager setPausesLocationUpdatesAutomatically:YES];
    //iOS 9（包含iOS 9）之后新特性：将允许出现这种场景，同一app中多个locationmanager：一些只能在前台定位，另一些可在后台定位，并可随时禁止其后台定位。
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        locationManager.allowsBackgroundLocationUpdates = YES;
    }
    
    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
    [locationManager requestLocationWithReGeocode:NO completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        NSString *latitude = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
        NSString *longitude = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
        DTCSAVE_OBJECT(longitude, @"longitude");
        DTCSAVE_OBJECT(latitude, @"latitude");
        NSLog(@"location:%f and %f", location.coordinate.longitude,location.coordinate.latitude);
        if (regeocode)
        {
            NSLog(@"reGeocode:%@", regeocode);
        }
    }];
}

// 获取周
- (NSString *)getWeek
{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEEE"];
    NSString *weekString = [dateFormatter stringFromDate:date];
    weekString = [weekString substringFromIndex:2];
    return weekString;
}

// 获取当前年月日
- (NSString *)getYearMouthDay{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *weekString = [dateFormatter stringFromDate:date];
    return weekString;
}


#pragma mark - 将某个时间转化成 时间戳
- (NSInteger)timeSwitchTimestamp:(NSString *)formatTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    return timeSp;
    
}

- (NSInteger) getNowTimeSp {
    NSDate* date = [NSDate date]; //------------将字符串按formatter转成nsdate
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    return timeSp;
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) { //在前台
        if ([notification.userInfo[@"report"] isEqualToString:@"disconnect"]) {
            if (DTCEXRACT_OBJECT(@"notDisturb") == nil || [DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"NO"]) {
                [self playNotifySound];
            }
            
            UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"警告" message:@"设备已断开连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alterView show];
            
        }
        //        @{@"remind":@"water"}
        if ([notification.userInfo[@"remind"] isEqualToString:@"喝水"] || [notification.userInfo[@"remind"] isEqualToString:@"吃药"]) {
            if (DTCEXRACT_OBJECT(@"notDisturb") == nil || [DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"NO"]) {
                [self playNotifySound];
            }
            
            UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提醒" message:[NSString stringWithFormat:@"一杯子提醒您该%@啦",notification.userInfo[@"remind"]] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alterView show];
        }
    }
    
}

- (void)playNotifySound {
    //获取路径
    NSString *path = [[NSBundle mainBundle] pathForResource:@"candoNotifySound" ofType:@"mp3"];
    //定义一个带振动的SystemSoundID
    SystemSoundID soundID = 1304;
    //判断路径是否存在
    if (path) {
        //创建一个音频文件的播放系统声音服务器
        OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)([NSURL fileURLWithPath:path]), &soundID);
        //判断是否有错误
        if (error != kAudioServicesNoError) {
            NSLog(@"%d",(int)error);
        }
    }
    //只播放声音，没振动
    AudioServicesPlaySystemSound(soundID);
}

@end
